
import React, { useCallback, useMemo } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import './App.css'

import Header from '../components/header/Header.jsx';

import CitySelector from '../components/city-selector/CitySelector.jsx';
import DateSelector from '../components/date-selector/DateSelector';

import Journey from './components/journey/Journey';
import Submit from './components/submit/Submit';
import HighSpeed from './components/high-speed/HighSpeed';
import DepartDate from './components/depart-date/DepartDate';

import { h0 } from '../common/fp';


import {
	from,
	to,
	hideCitySelector,
	hideDateSelector,
	showDateSelector,
	setDepartDate,
	fetchCityData,
	setSelectedCity,
	exchangeFromTo,
	showCitySelector,
	toggleHighSpeed,
} from './store/actions';

function App (props) {

	const {
		from,
		to,
		isCitySelectorVisible,
		isDateSelectorVisible,
		isLoadingCityData,
		cityData,
		departDate,
		highSpeed,
		dispatch
	} = props;

	const onBack = useCallback(() => {
		window.history.back()
	}, []);


	const cbs = useMemo(() => {
		return bindActionCreators(
			{
				exchangeFromTo,
				showCitySelector,
			},
			dispatch
		);
	}, []);

	const citySelectorCbs = useMemo(() => {
		return bindActionCreators(
			{
				onBack: hideCitySelector,
				fetchCityData,
				onSelect: setSelectedCity
			},
			dispatch
		)
	}, []);

	const departDateCbs = useMemo(() => {
		return bindActionCreators(
			{
				onClick: showDateSelector,
			},
			dispatch
		);
	}, []);

	const highSpeedCbs = useMemo(() => {
		return bindActionCreators({
			toggle: toggleHighSpeed,
		}, dispatch)
	}, [])

	const dateSelectorCbs = useMemo(() => {

		return bindActionCreators(
			{
				onBack: hideDateSelector,
			},
			dispatch
		);
	}, []);

	const onSelectDate = useCallback(day => {
		if (!day) {
			return;
		}

		if (day < h0()) {
			return;
		}

		dispatch(setDepartDate(day));
		dispatch(hideDateSelector());
	}, []);


	return (
		<div>
			<div className="header-wrapper">
				<Header title="火车票" onBack={onBack} />
			</div>
			<form action="./query.html" className="form">
				<Journey from={from} to={to} {...cbs} />
				<DepartDate time={departDate} {...departDateCbs} />
				<HighSpeed highSpeed={highSpeed} {...highSpeedCbs} />
				<Submit />
			</form>
			<CitySelector
				show={isCitySelectorVisible}
				cityData={cityData}
				isLoading={isLoadingCityData}
				{...citySelectorCbs}
			/>
			<DateSelector
				show={isDateSelectorVisible}
				{...dateSelectorCbs}
				onSelect={onSelectDate}
			/>
		</div>
	)
}

export default connect(
	function mapStateToProps (state, ownProps) {
		return state;
	},
	function mapDispatchToProps (dispatch) {
		return { dispatch }
	}
)(App);